﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace System
{
    public class Singleton<T> : Singleton
    {
        static T instance;
        public static T Instance
        {
            get { return instance; }
            set
            {
                instance = value;
                AllSingletons[typeof(T)] = value;
            }
        }
    }
    public class SingletonList<T> : Singleton<IList<T>>
    {
        static SingletonList()
        {
            Singleton<IList<T>>.Instance = new List<T>();
        }
        public new static IList<T> Instance
        {
            get { return Singleton<IList<T>>.Instance; }
        }
    }
    public class SingletonDictionary<TKey, TValue> : Singleton<IDictionary<TKey, TValue>>
    {
        static SingletonDictionary()
        {
            Singleton<Dictionary<TKey, TValue>>.Instance = new Dictionary<TKey, TValue>();
        }

        /// <summary>The singleton instance for the specified type T. Only one instance (at the time) of this dictionary for each type of T.</summary>
        public new static IDictionary<TKey, TValue> Instance
        {
            get { return Singleton<Dictionary<TKey, TValue>>.Instance; }
        }
    }
    public class Singleton
    {
        static Singleton()
        {
            allSingletons = new Dictionary<Type, object>();
        }
        static readonly IDictionary<Type, object> allSingletons;
        public static IDictionary<Type, object> AllSingletons
        {
            get { return allSingletons; }
        }
    }
    /// <summary>
    /// 对象池
    ///  ObjectPool<MyClass> pool = new ObjectPool<MyClass>(() => new MyClass());
    /// https://www.cnblogs.com/yyfh/p/11974574.html
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ObjectPool<T>
    {
        private ConcurrentBag<T> _object;
        private Func<T> _objectGenerator;

        public ObjectPool(Func<T> objectGenerator)
        {
            _object = new ConcurrentBag<T>();
            _objectGenerator = objectGenerator;
        }
        /// <summary>
        ///     取出
        /// </summary>
        /// <returns></returns>
        public T CheckOut()
        {
            T item;
            if (_object.TryTake(out item)) return item;
            return _objectGenerator();
        }
        /// <summary>
        ///     归还
        /// </summary>
        /// <param name="obj"></param>
        public void CheckIn(T obj)
        {
            _object.Add(obj);
        }

    }
}
